import {Component, OnInit, ViewEncapsulation, ChangeDetectionStrategy, ViewChild, OnDestroy} from '@angular/core';
import {imageUtil, DOWNLOAD_APP_PATH} from "@core/globals/globals.service";
import {ActivatedRoute, Router} from "@angular/router";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Subject} from "rxjs/Subject";
import {Subscription} from "rxjs/Rx";
import {ToolbarService} from "@shared/components/toolbar/toolbar.service";
import {CrowdSkuComponent} from "@crowd/crowd-sku/crowd-sku.component";
import {CrowdService} from "@crowd/crowd.service";
import {ToolsService} from "@shared/service/tools/tools.service";

@Component({
  selector: 'seed-step-2',
  templateUrl: './step-2.component.html',
  styleUrls: ['./step-2.component.scss', '../common.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class Step2Component implements OnInit, OnDestroy {
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public subscription: Subscription = new Subscription();
  public imageUtil = imageUtil.path;
  public stepForm2: FormGroup = new FormGroup({});
  public crowdSku = [];
  public creatIndex = 0;
  public hasGetInfo = false;
  public activeStartTime: any;
  @ViewChild(CrowdSkuComponent) child: CrowdSkuComponent;
  public params = {
    "crowdCode": "",
    "rightList": []
  };

  constructor(
    public router: Router,
    private formbuilder: FormBuilder,
    public crowdService: CrowdService,
    private route: ActivatedRoute,
    public toolBarService: ToolbarService,
    public toolsServices: ToolsService
  ) {
    this.route.queryParams.subscribe(param => {
      this.params.crowdCode = param['crowdCode'];
      this.activeStartTime = param['activeStartTime'];
    });
    /*this.route.queryParams.subscribe(param => {
      this.activeStartTime = param['activeStartTime'];
    });*/

    /**
     * @动态表单
     * @description 获取草稿信息，处理草稿信息价格单位转换，赋值给表单及保存参数params
     * @author baoww765
     * @date 2017-11-10
     */
    this.crowdService.getCrowdInfo(this.params.crowdCode)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data) {
        const rightList = res.data.twoReq.rightList;
        if (rightList && rightList.length > 0) {
          rightList.forEach(e => {
            e.price = e.price / 100;
            this.addSku(e);
          });
        } else {
          this.stepForm2.addControl(this.creatIndex.toString(), this.setControlForm());
          this.crowdSku.push(this.creatIndex.toString());
          this.creatIndex++;
        }
        this.hasGetInfo = true;
      }
    });
  }

  ngOnInit() {

  }

  /**
   * @description 初始化表单，动态赋值
   * @author baoww765
   * @date 2017-11-10
   * */
  setControlForm(each?: any) {
    const tempForm = this.formbuilder.group({
      rightName: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      price: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(4), Validators.min(1)]],
      quantity: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(3), Validators.min(1)]],
      buyTimesLimit: ['', [Validators.maxLength(3), Validators.min(1)]],
      sponsorType: ['0', [Validators.required]],
      rightDesc: ['', [Validators.maxLength(100)]]
    });
    for (const key in each) {
      if (key === 'buyTimesLimit') {
        if (each[key] === '0') {
          tempForm.controls[key].setValue('');
          continue;
        }
      }
      tempForm.controls[key].setValue(each[key]);
      if (key === 'sponsorType') {
        tempForm.controls['sponsorType'].setValue('0');
      }
    }
    return tempForm;
  }

  /**
   * @description 添加sku信息，动态设置表单控制器
   * @author baoww765
   * @date 2017-11-10
   * */
  addSku(each?: any) {
    this.crowdSku.push(this.creatIndex.toString());
    this.stepForm2.addControl(this.creatIndex.toString(), this.setControlForm(each));
    this.creatIndex++;
  }

  /**
   * @description 删除sku，删除对应表单控制器
   * @author baoww765
   * @date 2017-11-10
   * @param index 被删除sku对应index
   * */
  deleteSkuModule(index) {
    const controlName = this.crowdSku[index];
    this.crowdSku.splice(index, 1);
    this.stepForm2.removeControl(controlName);
  }

  /**
   * @description 保存第二步，将各个权益表信息赋值给保存参数对象params,保存之前转换价格单位，
   * 判断限购数量是否为空，为空则赋值为0
   * @author baoww765
   * @date 2017-11-13
   * */
  goToStep3() {
    const value = this.stepForm2.value;
    for (const key in value) {
      value[key]['price'] = value[key]['price'] * 100;
      if (value[key]['buyTimesLimit'] === '') {
        value[key]['buyTimesLimit'] = 0;
      }
      this.params.rightList.push(value[key]);
    }

    this.crowdService.saveTwo(this.params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.router.navigate([`/crowd/step-3`], {
          queryParams: {
            crowdCode: this.params.crowdCode,
            activeStartTime: this.activeStartTime
          }
        });
      } else {
        this.params.rightList = [];
        this.toolsServices.showToast(res.msg);
      }
    });
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}
